// 记录Vue构造函数
let _Vue = null

export default class VueRouter {
  constructor (options) {
    this.options = options || {}
    this.routeMap = {}
    this.data = _Vue.observable({
      current: '/'
    })
  }
  static install (Vue) {
    if (VueRouter.installed) {
      return
    }
    VueRouter.installed = true
    _Vue = Vue

    Vue.mixin({
      beforeCreate () {
        if (this.$options.router) {
          // 将router实例绑定到Vue的原型对象的属性上，所有的Vue实例都可以共享该$route属性
          Vue.prototype.$route = this.$options.router

          // 初始化router内部的事件
          this.$options.router._init()
        }
      }
    })
  }
  _init () {
    this.createRouteMap()
    this.initComponents()
    this.initEvent()
    this.setLocationHash()
  }
  setLocationHash () {
    if (this.options.routes.mode !== 'history') {
      window.location.hash = '#/'
    }
  }
  createRouteMap () {
    this.options.routes.forEach(element => {
      this.routeMap[element.path] = element.component
    })
  }
  initComponents () { // 运行时版本的vue不支持template 完整版本的编译器可以帮我们把template编译成render函数执行
    _Vue.component('router-link', {
      props: {
        to: String
      },
      render (h) {
        return h('a', {
          attrs: { // 第二个参数设置属性
            href: `#${this.to}`
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler (e) {
          window.location.hash = `#${this.to}`
          this.$route.data.current = this.to
          e.preventDefault()
        }
      }
    })

    const self = this
    _Vue.component('router-view', {
      render (h) {
        const component = self.routeMap[self.data.current]
        return h(component)
      }
    })
  }

  initEvent () {
    window.addEventListener('hashchange', () => {
      if (window.location.hash) {
        const path = window.location.hash.substr(1)
        this.data.current = path
      }
    })
  }
}
